// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.linqingying.gitcode.pullrequest.ui.selector

import com.intellij.collaboration.async.combineState
import git4idea.remote.hosting.ui.RepositoryAndAccountSelectorViewModelBase
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.StateFlow
import org.jetbrains.annotations.ApiStatus
import com.linqingying.gitcode.authentication.accounts.GCAccountManager
import com.linqingying.gitcode.authentication.accounts.GitCodeAccount
import com.linqingying.gitcode.util.GCGitRepositoryMapping
import com.linqingying.gitcode.util.GCHostedRepositoriesManager

@ApiStatus.Experimental
class GCRepositoryAndAccountSelectorViewModel internal constructor(
  scope: CoroutineScope,
  repositoriesManager: GCHostedRepositoriesManager,
  accountManager: GCAccountManager,
  onSelected: suspend (GCGitRepositoryMapping, GitCodeAccount) -> Unit
) : RepositoryAndAccountSelectorViewModelBase<GCGitRepositoryMapping, GitCodeAccount>(
  scope,
  repositoriesManager,
  accountManager,
  onSelected) {

  val gitcodeLoginAvailableState: StateFlow<Boolean> =
    combineState(scope, repoSelectionState, accountSelectionState, missingCredentialsState, ::isGitCodeLoginAvailable)

  private fun isGitCodeLoginAvailable(repo: GCGitRepositoryMapping?, account: GitCodeAccount?, credsMissing: Boolean?): Boolean {
    if (repo == null) return false
    return repo.repository.serverPath.isGitCodeDotCom && (account == null || credsMissing == true)
  }

  val gheLoginAvailableState: StateFlow<Boolean> =
    combineState(scope, repoSelectionState, accountSelectionState, missingCredentialsState, ::isGheLoginVisible)


  private fun isGheLoginVisible(repo: GCGitRepositoryMapping?, account: GitCodeAccount?, credsMissing: Boolean?): Boolean {
    if (repo == null) return false
    return !repo.repository.serverPath.isGitCodeDotCom && (account == null || credsMissing == true)
  }
}
